package com.agrm.member.controller;

import com.agrm.member.service.MemberService;
import com.agrm.model.common.dtos.PageRequestDto;
import com.agrm.model.common.dtos.PageResponseResult;
import com.agrm.model.common.dtos.ResponseResult;
import com.agrm.model.member.dto.MemberDto;
import com.agrm.model.member.dto.MemberQuery;
import com.agrm.model.member.pojo.Member;
import com.agrm.model.user.dto.UserSafeDto;
import com.agrm.model.user.pojo.User;
import com.agrm.utils.JwtUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/member")
public class MemberController {

    @Autowired
    private MemberService memberService;
    @Value("${jwt.secretKey}")
    private String secretKey;
    private final RedisTemplate<String, Object> redisTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public MemberController(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    private final StrongPasswordEncryptor pe = new StrongPasswordEncryptor();


    /**
     * 用户注册接口
     * @param member
     * @return
     */
    @PostMapping("/register")
    public ResponseResult register(@RequestBody MemberDto member) {
        // 从Redis中获取并删除验证码，captchaId是验证码的唯一标识
        String captcha = (String) redisTemplate.opsForValue().getAndDelete("captcha-" + member.getCaptchaId());
        // 验证码校验，如果验证码不匹配则返回错误信息
        if (!member.getCaptcha().equals(captcha)) {
            return ResponseResult.errorResult(300, "验证码错误");
        }
        String email = member.getEmail();
        String emailCode = member.getEmailCode();
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps("login:email:captcha:"+email);
        String code = hashOps.get("captcha");
        if(!Objects.equals(code, emailCode)){
            return ResponseResult.errorResult(300,"邮箱验证码错误！");
        }
        // 根据用户名查询用户信息
        Member byAccount = memberService.getOne(Wrappers.<Member>lambdaQuery().eq(Member::getAccount, member.getAccount()));

        // 判断用户是否存在，不存在则返回错误信息
        if (byAccount != null) {
            return ResponseResult.errorResult(300, "用户已存在！");
        }
        Member trueMember = new Member();
        BeanUtils.copyProperties(member, trueMember);
        trueMember.setPassword(pe.encryptPassword(member.getPassword()));
        if (memberService.save(trueMember)) {
            return ResponseResult.okResult(200,"注册成功！");
        }
        return ResponseResult.errorResult(300,"注册失败！");
    }



    /**
     * 用户登录接口
     *
     * @param member 包含用户登录信息的请求体，包含用户名、密码和验证码信息
     * @return 返回ResponseResult，包含登录结果或错误信息
     */
    @PostMapping("/login")
    public ResponseResult login(@RequestBody MemberDto member) {
        // 从Redis中获取并删除验证码，captchaId是验证码的唯一标识
//        String captcha = (String) redisTemplate.opsForValue().getAndDelete("captcha-" + member.getCaptchaId());
//        // 验证码校验，如果验证码不匹配则返回错误信息
//        if (!member.getCaptcha().equals(captcha)) {
//            return ResponseResult.errorResult(-1, "验证码错误");
//        }
//        String email = member.getEmail();
//        String emailCode = member.getEmailCode();
//        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps("login:email:captcha:"+email);
//        String code = hashOps.get("captcha");
//        if(!Objects.equals(code, emailCode)){
//            return ResponseResult.errorResult(-1,"邮箱验证码错误！");
//        }

        // 根据用户名查询用户信息
        Member byAccount = memberService.getOne(Wrappers.<Member>lambdaQuery().eq(Member::getAccount, member.getAccount()));

        memberService.getById(byAccount.getId());

        // 判断用户是否存在，不存在则返回错误信息
        if (byAccount == null) {
            return ResponseResult.errorResult(-1, "用户不存在");
        }
        // 校验密码，使用pe工具类的checkPassword方法进行密码验证
        if (!pe.checkPassword(member.getPassword(), byAccount.getPassword())) {
            return ResponseResult.errorResult(-1, "密码错误");
        }

        // 生成JWT令牌，包含用户ID、用户名等信息，设置30分钟过期时间
        String jwt = JwtUtil.createJwt(member.getAccount(), UUID.randomUUID().toString(),
                Map.of("id", byAccount.getId(), "username", byAccount.getAccount()), LocalDateTime.now().plusMinutes(30), secretKey);
        // 返回成功响应，包含生成的JWT令牌
        Map<String , Object> res = new HashMap<>();
        res.put("token",jwt);
        res.put("userId" , byAccount.getId());
        res.put("username",byAccount.getAccount());
        return ResponseResult.okResult(res);
    }


    /**
     * 根据id查询会员信息
     * @param id
     * @return
     */
    @GetMapping("/get")
    public ResponseResult getById(@RequestParam("id") Integer id){
        return ResponseResult.okResult(memberService.getById(id));
    }

    /**
     * 查询所有会员信息
     * @return
     */
    @GetMapping("/all")
    public ResponseResult getAll(){
        return ResponseResult.okResult(memberService.list());
    }

    /**
     * 分页条件查询会员信息
     * @param page 分页参数
     * @param query 查询参数
     * @return 分页数据
     */
    @GetMapping("/list")
    public PageResponseResult list(PageRequestDto page,MemberQuery query){
        IPage<Member> pages = memberService.pageQueryList(page, query);
        PageResponseResult pageResponseResult = new PageResponseResult(page.getPage(),page.getSize(),(int)pages.getTotal());
        pageResponseResult.setData(pages.getRecords());

        return pageResponseResult;
    }

    /**
     * 添加会员信息
     * @param member
     * @return
     */
    @PostMapping("/add")
    public ResponseResult add(@RequestBody Member member){
        return ResponseResult.okResult(memberService.save(member));
    }

    /**
     * 修改会员信息
     * @param member
     * @return
     */
    @PutMapping("/update")
    public ResponseResult update(@RequestBody Member member){
        return ResponseResult.okResult(memberService.updateById(member));
    }

    /**
     * 删除会员信息
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    public ResponseResult delete(Integer id){
        return ResponseResult.okResult(memberService.removeById(id));
    }


    @GetMapping("/docs/README.md")
    public String getAboutUs(){
        String data = "### 介绍\n" +
                "\n" +
                "[STMall](https://gitee.com/agrm/stmall.git)\n" +
                "\n" +
                "### 快速开始\n" +
                "\n" +
                "1. 创建数据库agrm_member\n" +
                "\n" +
                "2. 创建表\n";
        return data;
    }

}
